package com.qf.dao.impl;

import com.qf.dao.CustomerDao;

import com.qf.pojo.Customer;
import com.qf.utils.DataSourceUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class CustomerDaoImpl implements CustomerDao {
    private QueryRunner qr=new QueryRunner(DataSourceUtil.getDataSource());
    @Override
    public List<Customer> findListByTypeId(int startIndex, int pageSize) {
        String sql = "SELECT * FROM customer limit ?,? ";
        try {
            return  qr.query(sql, new BeanListHandler<>(Customer.class),startIndex,pageSize);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    @Override
    public long findTotalCount() {
        String sql = "SELECT count(0) FROM customer";
        try {
            long count = (long) qr.query(sql, new ScalarHandler());
            return count;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }


    @Override
    public void insert(Customer customer) {
        String sql = "insert into customer values(?,?,?,?,?,?,?,?,?,?,?,?)";
        try {
            qr.update(sql, null, customer.getCus_name(), customer.getCus_type_id(),
                    customer.getTag_id(), customer.getState_id(), customer.getTel(),
                    customer.getEmp_id(), customer.getTeam_id(), customer.getCus_age(),
                    customer.getCus_location(), customer.getCus_company(), customer.getCus_position());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Customer findCustomer(String cusId) {
        String sql = "select * from customer where cus_id=?";
        try {
            return qr.query(sql,new BeanHandler<>(Customer.class),cusId);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void update(Customer customer) {
        String sql="update customer set cus_name=?,cus_type_id=?,tag_id=?,state_id=?,tel=?,emp_id=?,team_id=?,cus_age=?,cus_location=?,cus_company=?,cus_position=? where cus_id=?";
        try {
            qr.update(sql,customer.getCus_name(),customer.getCus_type_id(),customer.getTag_id(),
                    customer.getState_id(),customer.getTel(),customer.getEmp_id(),
                    customer.getTeam_id(),customer.getCus_age(),customer.getCus_location(),
                    customer.getCus_company(),customer.getCus_position(),customer.getCus_id());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
